package ltd.hxya.novel.common.framework;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义Future类，实现在异步代码执行之前，将主线程中的requestAttribute放到子线程中
 * @param <T>
 */
public class CustomFuture<T>  {

    public static void runExec(Runnable runnable,ThreadPoolExecutor threadPoolExecutor){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture.runAsync(()->{
            RequestContextHolder.setRequestAttributes(requestAttributes);
        },threadPoolExecutor).thenRun(runnable);
    }


    public  static CompletableFuture<Void> supplyExec(ThreadPoolExecutor threadPoolExecutor){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);

        },threadPoolExecutor);
        return completableFuture;
    }

}
